package com.ita.acmsystem.merchant.util;

import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ita.acmsystem.merchant.servlet.RegisterServlet;

public class AsyncFileUploadUtil {
	// 上传文件存储目录
	private static final String MERCHANT_PICTURE_DIRECTORY = "merchant";
	private static final String IDCARD_PICTURE_DIRECTORY = "idcard";
	private static final String FOOD_PICTURE_DIRECTORY = "foodpic";

	// 上传配置
	private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
	private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

	public static Map<String, String> getFileUploadPathByAsync(
			HttpServletRequest request, HttpServletResponse response,
			String realPath) throws Exception {
		// realPath : getServletContext().getRealPath("/") , 这个路径相对当前应用的目录

		ObjectMapper mapper = new ObjectMapper();
		Map<String, String> responseJsonMap = new HashMap<String, String>();
		Map<String, String> resultMap = new HashMap<String, String>();
		PrintWriter writer = response.getWriter();

		// 检测是否为多媒体上传
		if (!ServletFileUpload.isMultipartContent(request)) {
			// 如果不是则停止

			// writer.println("Error: 表单必须包含 enctype=multipart/form-data");
			// writer.flush();
			responseJsonMap.put("status", "false");
			responseJsonMap.put("msg", "该表单enctype类型错误");
			writer.write(mapper.writeValueAsString(responseJsonMap));
			writer.flush();
			return null;
		}

		// 配置上传参数
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
		factory.setSizeThreshold(MEMORY_THRESHOLD);
		// 设置临时存储目录
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置最大文件上传值
		upload.setFileSizeMax(MAX_FILE_SIZE);
		// 设置最大请求值 (包含文件和表单数据)
		upload.setSizeMax(MAX_REQUEST_SIZE);
		// 中文处理
		upload.setHeaderEncoding("UTF-8");

		// 构造临时路径来存储上传的文件
		// 这个路径相对当前应用的目录
		String merchantPath = realPath + File.separator
				+ MERCHANT_PICTURE_DIRECTORY;
		String idcardPath = realPath + File.separator
				+ IDCARD_PICTURE_DIRECTORY;
		String foodPicPath = realPath + File.separator + FOOD_PICTURE_DIRECTORY;
		// 如果目录不存在则创建
		File merchantDir = new File(merchantPath);
		if (!merchantDir.exists()) {
			merchantDir.mkdir();
		}
		File idcardDir = new File(idcardPath);
		if (!idcardDir.exists()) {
			idcardDir.mkdir();
		}
		File foodPicDir = new File(foodPicPath);
		if (!foodPicDir.exists()) {
			foodPicDir.mkdir();
		}

		// 获取表单中的文本字段
		String id = UUID.randomUUID().toString();
		File merchantFile = null;
		File idcardFile = null;
		File foodPicFile = null;

		String merchantPicSavePath = null;
		String idcardPicSavePath = null;
		String foodPicSavePath = null;

		// 解析请求的内容提取文件数据
		List<FileItem> formItems = null;
		formItems = upload.parseRequest(request);
		if (formItems != null && formItems.size() > 0) {
			// 迭代表单数据
			for (FileItem item : formItems) {
				// 处理不在表单中的字段
				if (!item.isFormField()) {
					System.out.println("文件字段名字：" + item.getFieldName());
					if ("headPic".equals(item.getFieldName())) {
						String fileName = id;
						String filePath = merchantPath + File.separator + id;

						// 从配置文件中获得host和port
						// InputStream is =
						// RegisterServlet.class.getClassLoader()
						// .getResourceAsStream("property.propertties");
						Properties prop = new Properties();
						// prop.load(is);
						prop.load(AsyncFileUploadUtil.class
								.getResourceAsStream("/property.propertties"));

						String host = prop.getProperty("host");
						String port = prop.getProperty("port");

						// 入库地址
						merchantPicSavePath = "http://" + host + ":" + port
								+ "/./merchant/" + id;

						resultMap.put("type", "headPic");
						resultMap.put("path", merchantPicSavePath);
						responseJsonMap.put("status", "true");
						responseJsonMap.put("path", merchantPicSavePath);

						File storeFile = new File(filePath);
						// 在控制台输出文件的上传路径
						System.out.println(filePath);
						System.out.println(merchantPicSavePath);
						// 保存文件到硬盘
						item.write(storeFile);
						merchantFile = storeFile;
					} else if ("idCard".equals(item.getFieldName())) {
						String fileName = id;
						String filePath = idcardPath + File.separator
								+ fileName;

						// 从配置文件中获得host和port
						// InputStream is =
						// RegisterServlet.class.getClassLoader()
						// .getResourceAsStream("property.propertties");
						Properties prop = new Properties();
						// prop.load(is);
						prop.load(AsyncFileUploadUtil.class
								.getResourceAsStream("/property.propertties"));

						String host = prop.getProperty("host");
						String port = prop.getProperty("port");

						// 入库地址
						idcardPicSavePath = "http://" + host + ":" + port
								+ "/./idcard/" + id;

						resultMap.put("type", "idCard");
						resultMap.put("path", idcardPicSavePath);
						responseJsonMap.put("status", "true");
						responseJsonMap.put("path", idcardPicSavePath);

						File storeFile = new File(filePath);
						// 在控制台输出文件的上传路径
						System.out.println(filePath);
						System.out.println(idcardPicSavePath);
						// 保存文件到硬盘
						item.write(storeFile);
						idcardFile = storeFile;
					} else if ("foodPic".equals(item.getFieldName())) {
						String fileName = id;
						String filePath = foodPicPath + File.separator + id;

						// 从配置文件中获得host和port
						// InputStream is =
						// RegisterServlet.class.getClassLoader()
						// .getResourceAsStream("property.propertties");
						Properties prop = new Properties();
						// prop.load(is);
						prop.load(AsyncFileUploadUtil.class
								.getResourceAsStream("/property.propertties"));
						
						String host = prop.getProperty("host");
						String port = prop.getProperty("port");

						// 入库地址
						foodPicSavePath = "http://" + host + ":" + port
								+ "/./foodpic/" + id;

						resultMap.put("type", "foodpic");
						resultMap.put("path", foodPicSavePath);
						responseJsonMap.put("status", "success");
						responseJsonMap.put("path", foodPicSavePath);

						File storeFile = new File(filePath);
						// 在控制台输出文件的上传路径
						System.out.println(filePath);
						System.out.println(foodPicSavePath);
						// 保存文件到硬盘
						item.write(storeFile);
						merchantFile = storeFile;
					}
				}
			}
		}
		writer.write(mapper.writeValueAsString(responseJsonMap));
		writer.flush();
		return resultMap;
	}
}
